package labb3.FileHandling;

import labb3.Media;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 * @author Mikko Puustinen
 * @version 0.5, 2007-okt-18
 */
public class SaveSerialized implements CollectionSaver {
    private final String path;

    /**
     * Constructs a SaveSerialized for later use. The specified path will then
     * be used.
     *
     * @param path location of the file.
     */
    public SaveSerialized(String path) {
        this.path = path;
    }

    /**
     * Save (serialized) Media to a file using ObjectOutPutStream.
     *
     * @param media Media to save.
     *
     * @throws IOException if error occurs while saving.
     * @see java.io.Serializable
     */
    public void saveCollection(ArrayList<Media> media) throws IOException {
        File file = new File(path);
        if (!file.canWrite() && file.exists())
            throw new IOException("Couldn't write to file (read-only?)");

        FileOutputStream fos;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(path);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(media);
        } catch (IOException e) {
            throw new IOException("Error while writing to file");
        } finally {
            if (oos != null) {
                oos.close();
            }
        }
    }
}
